package GroupChats;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ThreadServer extends Thread{
    private Socket socket ;
    public ThreadServer(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            DataInputStream dis = new DataInputStream(inputStream);
            while (true){
                try {
                    String str = dis.readUTF();
                    System.out.println(" 来自主机IP为:"+socket.getInetAddress().getHostAddress() +
                            " ，主机名为:" + socket.getInetAddress().getHostName() + ",端口号为:" + socket.getPort() + "发送的信息:"+str);

                    //将消息发送到每个客户端中
                    sendClient(str);
                } catch (IOException e) {
                    System.out.println(socket.getRemoteSocketAddress()+" 已下线了 !!!!");
                    Server.socketList.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendClient(String str) throws IOException {
        for (Socket s : Server.socketList) {
            OutputStream os = s.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(str);
            dos.flush();
        }
    }
}
